package com.douing.ad.dsp.bidding.rtb;

import com.douing.ad.dsp.bidding.dto.ConfigInfo;
import com.douing.ad.dsp.bidding.tj.utils.NodeData;
import com.douing.ad.dsp.bidding.utils.ApplicationContextUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class Common {
    private static final Logger logger = LoggerFactory.getLogger(Common.class);

    public static ConfigInfo configInfo = ApplicationContextUtils.getBean(ConfigInfo.class);

    public static long GetCityId(String ip) {
        Long ipLong = ipToLong(ip);
        Map<Long, Long[]> map = TxtUtil.map;
        Long end = Long.parseLong(map.size()-1 + "");
        Long areaid = CalculationUtil.binSearch(map, 1l, end, ipLong);
        if(areaid == 100000l){
            areaid = 0l;
        }
        return areaid;
    }

    public static String GetCurrentWeekOfDate(Calendar cal) {
        String[] weekDays = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static String GetCurrentDate(Date dt) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        return df.format(dt);
    }

    public static String GetCurrentHour(Calendar cal) {
        String chour = "";
        int ret = cal.get(Calendar.HOUR_OF_DAY);
        if (ret < 10) {
            chour = "0" + ret;
        } else {
            chour = "" + ret;
        }
        return chour;
    }

    public static boolean OutOfTime(long starttime, NodeData nodeData) {
        long timespan = System.currentTimeMillis() - starttime;
        boolean ret = timespan > configInfo.getTmax();
        if (ret) {
            WriteError("out of time,time is " + timespan);
            // TODO
            nodeData.setIsTimeOut(1);
        }
        return ret;
    }

    public static long ipToLong(String strIp){  
        String[] ip = strIp.split("\\.");
        return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
    }  
    
    
    public static void WriteLog(String s) {
        logger.info(s);
    }

    public static void WriteError(String s) {
        logger.error(s);
    }

    public static void WriteError(String s, Exception ex) {
        logger.error(s, ex);
    }

}
